﻿using System;
using Microsoft.Xna.Framework;
using WindowsGame.Data;
using WindowsGame.Static;
using WindowsGame.Library;

namespace WindowsGame.Manager
{
	/// <summary>
	/// ScreenManager is responsible for managing all screens in game.
	/// </summary>
	public interface IScreenManager
	{
		void LoadContent();
		void UnloadContent();
		void Update(GameTime gameTime);
		void Draw();
	}

	public class ScreenManager : IScreenManager
	{
		private readonly IDataManager dataManager;
		private readonly IGameObjectManager gameObjectManager;
		private readonly IInputManager inputManager;
		private Boolean start;

		public ScreenManager(IDataManager dataManager, IGameObjectManager gameObjectManager, IInputManager inputManager)
		{
			this.dataManager = dataManager;
			this.gameObjectManager = gameObjectManager;
			this.inputManager = inputManager;
		}

		public void LoadContent()
		{
			Assets.LoadContent();
			LoadData();
		}
		public void UnloadContent()
		{
			Engine.Content.Unload();
		}

		// Update each game object using GameObjectManager.
		public void Update(GameTime gameTime)
		{
			inputManager.Update(gameTime);
			Boolean escape = inputManager.Escape();
			if (escape)
			{
				Engine.Game.Exit();
				return;
			}

			Boolean load = inputManager.Load();
			if (load)
			{
				LoadData();
				return;
			}

			Boolean toggle = inputManager.Toggle();
			if (toggle)
			{
				start = !start;
				gameObjectManager.Reset();
			}
			if (!start)
			{
				return;
			}

			gameObjectManager.Update(gameTime);
		}

		// Draw each game object using GameObjectManager.
		public void Draw()
		{
			Engine.GraphicsDevice.Clear(Color.CornflowerBlue);

			Engine.SpriteBatch.Begin();
			gameObjectManager.Draw();
			Engine.SpriteBatch.End();
		}

		private void LoadData()
		{
			String boardFile = GetPath("BoardData.txt");
			String snakeFile = GetPath("SnakeData.xml");

			String[] files = new[] { boardFile, snakeFile };
			AllData data = dataManager.LoadData(files);

			gameObjectManager.LoadData(data);
			start = false;
		}
		private static String GetPath(String name)
		{
			return GetPath(Constants.DATA_DIRECTORY, name);
		}
		private static String GetPath(String fldr, String name)
		{
			String root = String.Empty;
			String path = String.Format("{0}/{1}/{2}", Constants.ROOT_DIRECTORY, fldr, name);

			return String.Format("{0}{1}", root, path);
		}
	}
}